package exercise;

import java.util.Comparator;
import java.util.PriorityQueue;

//建立比较器创创建大根堆
class GreaterIntCmp implements Comparator<Integer>{
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2 - o1;
    }
}

public class priority {
    //topK min
    public int[] minK(int[] arr, int k){
        int[] ret = new int[k];
        if(arr == null || k == 0){
            return ret;
        }
        //建立大根堆
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new GreaterIntCmp());
        //使用前k个元素创建大根堆
        for(int i = 0; i < k; i++){
            priorityQueue.offer(arr[i]);
        }
        //后面N - K个元素与堆顶元素进行比较
        for(int i = k; i < arr.length; i++){
            if(arr[i] < priorityQueue.peek()){
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        //将优先级队列中的元素放入数组中
        for(int i = 0; i < k; i++){
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }
}
